<?php
/**
 * 首页管理
 * User: cxm
 * Date: 2019/10/18
 * Time: 17:17
 */
namespace App\Http\Controllers\Admin\Index;
use App\Http\Controllers\Admin\Controller;
use App\Http\Resources\Admin\AdminUserResource;
use App\Models\Admin;
use App\Models\AdminPermission;
use App\Models\AdminRolePermission;
use App\Models\AdminUser;
use App\Models\Auth;
use App\Models\AwardHistory;
use App\Models\Delivery;
use App\Models\Menu;
use App\Models\Order;
use App\Models\Policy;
use App\Models\Subject;
use App\Models\Trader;
use App\Models\TraderGoods;
use App\Models\User;
use App\Models\UserDrawRecord;
use DB,Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class IndexController extends  Controller {
    /**
     * 后台首页相关数据
     * URL GET:/admin/todayStatistic
     * @return mixed
     */
    public function index(){
        $date = date('Y-m-d', time());
        $data = [
            'count' => [
                'create_user'   => User::whereDate('created_at',$date)->count(),// 今日新增用户
                'award_count'   => AwardHistory::whereDate('created_at',$date)->count(), // 今日中奖人数
                'draw_award'    => AwardHistory::whereDate('created_at',$date)->where('status',1)->count(), // 今日领奖人数
            ]
        ];
        return $this->success('查询成功',$data);
    }

    /**
     * 固定奖励、随机奖励抽奖人数
     * URL POST:/admin/awardTypeStatistics
     * @return mixed
     */
    public function awardTypeStatistics(){
        $name = ['固定奖励','随机奖励'];

        $newArr = [
            [
                'name'      => '固定奖励',
                'value'     => 1,
            ],
            [
                'name'      => '随机奖励',
                'value'     => 2
            ],
        ];
        $data = [
            'name'      => $name,
            'arr'       => $newArr
        ];
        return $this->success('查询成功',$data);
    }

    /**
     * 参与人数、中奖人数、兑奖人数
     * URL POST:/admin/peopleStatistics
     * @return mixed
     */
    public function peopleStatistics(){
        $name = ['参与人数','中奖人数','兑奖人数'];
        $date = date('Y-m-d', time());
        $newArr = [
            [
                'name'      => '参与人数',
                'value'     => UserDrawRecord::whereDate('created_at',$date)->groupBy('user_id')->count(),
            ],
            [
                'name'      => '中奖人数',
                'value'     => AwardHistory::whereDate('created_at',$date)->count(),
            ],
            [
                'name'      => '兑奖人数',
                'value'     => AwardHistory::whereDate('created_at',$date)->where('status',1)->count(),
            ],
        ];
        $data = [
            'name'      => $name,
            'arr'       => $newArr
        ];
        return $this->success('查询成功',$data);
    }

    /**
     * 获取左侧菜单
     * URL GET:/admin/getLeftMenu
     * @return mixed
     */
    public function getLeftMenu(){
        // 所得权限
        $data = AdminPermission::getLeftMenu();
        return $this->success('查询成功',$data);
    }

    /**
     * 获取所有的权限
     * URL GET:/admin/allPermission
     * @param int role_id 权限ID
     * @return mixed
     */
    public function allPermission(){
        $role_id = request()->post('role_id', 0);
        // 当前用户的权限
        //$menu_ids = AdminRolePermission::getAuthorityMenuId(auth('admin')->user()->id);
        //$permissions = AdminPermission::getRoleMenu(0, $menu_ids, $role_id);
        // 指定角色的权限
        $role_permissions = AdminRolePermission::getPermissionByRoleId($role_id);
        $permissions = AdminPermission::getRoleMenus( $role_permissions );
        $data['list'] = $permissions;
        return $this->success('查询成功',$data);
    }

    /**
     * 管理员信息
     * URL GET:/admin/userInfo
     * @return mixed
     */
    public function adminInfo(){
        $admin_info = $this->userModel();
        $data = AdminUserResource::make($admin_info);
        return $this->success('查询成功',$data);
    }

    /**
     * 修改管理员信息
     * URL POST:/admin/editUserInfo
     * @param Request $request
     * @param string username 登录账号
     * @param string name 昵称
     * @param int avatar 头像
     * @param string phone 手机号
     * @param string password 密码
     * @return mixed
     */
    public function editUserInfo(Request $request){
        $params = $request->only(['username','name','avatar','phone','password']);
        $user_id = $this->userId();
        if(!$user_id) {
            return $this->error('登录失效，请重新登录');
        }
        if ($this->userModel()->status == 2) {
            return $this->error('该账号已冻结，请联系管理员');
        }
        if (!array_key_exists('phone',$params) && !empty($params['phone']) && preg_match("/^1\d{10}$/", $params['phone'])) {
            return $this->error('手机格式错误');
        }
        if (array_key_exists('password',$params) && !empty($params['password'])) {
            $params['password'] = bcrypt($params['password']);
        }
        $where = [];
        $where[] = ['id',$user_id];
        $data = AdminUser::updated($where,$params);
        if (!$data) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

    /**
     * 修改密码
     * URL POST:/admin/editPassword
     * @param Request $request
     * @param string old_password 旧密码
     * @param string new_password 新密码
     * @return mixed
     */
    public function editPassword(Request $request){
        $params = $request->only(['old_password','new_password']);
        $validator = Validator::make($params,[
            'old_password'          => ['required'],
            'new_password'          => ['required']
        ],[
            'old_password.required' => '旧密码不能为空',
            'new_password.required' => '新密码不能为空'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $admin_id = $this->userId();
        $admin_user = AdminUser::find($admin_id);
        if (!Hash::check($params['old_password'],$admin_user->password)) {
            return $this->error('旧密码错误');
        }
        $where = [];
        $where[] = ['id',$admin_id];
        $field = [
            'password'  => bcrypt($params['password'])
        ];
        $result = AdminUser::updated($where,$field);
        if (!$result) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

    /**
     * 面包屑
     * URL POST:/admin/getCrumbs
     * @param Request $request
     * @return mixed
     */
    public function getCrumbs(Request $request)
    {
        $route = $request->post('route', '');
        $data = AdminPermission::getCrumbs($route);
        return $this->success('查询成功',['list' => $data]);
    }

    /**
     * 面包屑
     * URL POST:/admin/getCrumbsIds
     * @param Request $request
     * @return mixed
     */
    public function getCrumbsIds(Request $request)
    {
        $route = $request->post('route', '');
        $data = AdminPermission::getCrumbs($route);
        $crumbs_ids = [];
        $crumbs_id = AdminPermission::where('url', $route)->value('id');
        if ($data) {
            foreach ($data as $key => $val) {
                $crumbs_ids[] = $val['id'];
            }
        }
        $list['list']['crumbs_ids'] = $crumbs_ids;
        $list['list']['crumbs_id'] = $crumbs_id;
        return $this->success('查询成功',$list);
    }
}